'use strict';
// const fs = require('fs');
const Controller = require('egg').Controller;

class PageDataController extends Controller {
  
  async add() {
    const queryObj = this.ctx.request.body.page_id ? this.ctx.request.body : this.ctx.query;
    const result = await this.app.mysql.insert('page_data', queryObj);
    this.ctx.body = this.ctx.success(result);
  }

  async delete() {
    const queryObj = this.ctx.request.body.id ? this.ctx.request.body : this.ctx.query;
    let sql =  `delete  from page_data where id = "${queryObj.id}"`
    const result = await this.app.mysql.query(sql)
    this.ctx.body = this.ctx.success(result);
  }

  async update() {
    const queryObj = (this.ctx.request.body.id || this.ctx.request.body.ids) ? this.ctx.request.body : this.ctx.query;
    console.log(queryObj);
    if(queryObj.ids){
      let sql =  `UPDATE page_data set order_num=CASE`;

      queryObj.ids.split(",").forEach((v,index) => {
        sql +=  ` when id = ${v} then ${index+1} `
      });
      sql += `end  where id in (${queryObj.ids})`      
      console.log(sql);
      const result = await this.app.mysql.query(sql)
      this.ctx.body = this.ctx.success(result);
    }else{
      const result = await this.app.mysql.update('page_data', queryObj);
      this.ctx.body = this.ctx.success(result);
    }
    
  }

}

module.exports = PageDataController;
